#!/bin/bash
# ========================================
# 前端部署脚本
# ========================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目路径配置
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_ROOT=$(cd "$SCRIPT_DIR/.." && pwd)
FRONTEND_DIR="$PROJECT_ROOT/ruoyi-ui"

# 部署配置
DEPLOY_DIR="/usr/share/nginx/html/ruoyi"
NGINX_CONF_DIR="/etc/nginx/conf.d"
BACKUP_DIR="/backup/ruoyi-ui"

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_message "$RED" "❌ 错误: $1 未安装，请先安装"
        exit 1
    fi
}

# 检查node和npm是否安装
check_dependencies() {
    print_message "$BLUE" "📦 检查依赖..."
    check_command node
    check_command npm
    print_message "$GREEN" "✅ 依赖检查通过"
}

# 检查前端目录是否存在
check_frontend_dir() {
    if [ ! -d "$FRONTEND_DIR" ]; then
        print_message "$RED" "❌ 错误: 前端目录不存在 $FRONTEND_DIR"
        exit 1
    fi
    print_message "$GREEN" "✅ 前端目录: $FRONTEND_DIR"
}

# 安装依赖
install_dependencies() {
    print_message "$BLUE" "📦 安装前端依赖..."
    cd "$FRONTEND_DIR"
    
    if [ -f "package-lock.json" ]; then
        npm ci
    elif [ -f "yarn.lock" ]; then
        yarn install
    elif [ -f "pnpm-lock.yaml" ]; then
        pnpm install
    else
        npm install
    fi
    
    print_message "$GREEN" "✅ 依赖安装完成"
}

# 构建前端
build_frontend() {
    print_message "$BLUE" "🔨 开始构建前端..."
    cd "$FRONTEND_DIR"
    
    # 清理旧的构建文件
    if [ -d "dist" ]; then
        rm -rf dist
    fi
    
    # 执行构建
    npm run build:prod
    
    if [ ! -d "dist" ]; then
        print_message "$RED" "❌ 构建失败: dist目录不存在"
        exit 1
    fi
    
    print_message "$GREEN" "✅ 前端构建完成"
}

# 备份旧版本
backup_old_version() {
    if [ -d "$DEPLOY_DIR" ]; then
        print_message "$BLUE" "💾 备份旧版本..."
        mkdir -p "$BACKUP_DIR"
        BACKUP_FILE="$BACKUP_DIR/ruoyi-ui-$(date +%Y%m%d_%H%M%S).tar.gz"
        tar -czf "$BACKUP_FILE" -C "$(dirname $DEPLOY_DIR)" "$(basename $DEPLOY_DIR)"
        print_message "$GREEN" "✅ 备份完成: $BACKUP_FILE"
    fi
}

# 部署到Nginx
deploy_to_nginx() {
    print_message "$BLUE" "🚀 部署到Nginx..."
    
    # 创建部署目录
    mkdir -p "$DEPLOY_DIR"
    
    # 复制构建文件
    cd "$FRONTEND_DIR"
    cp -r dist/* "$DEPLOY_DIR/"
    
    # 设置权限
    chown -R nginx:nginx "$DEPLOY_DIR" 2>/dev/null || chown -R www-data:www-data "$DEPLOY_DIR" 2>/dev/null || true
    
    print_message "$GREEN" "✅ 部署完成: $DEPLOY_DIR"
}

# 配置Nginx
configure_nginx() {
    print_message "$BLUE" "⚙️  配置Nginx..."
    
    NGINX_CONF="$NGINX_CONF_DIR/ruoyi.conf"
    
    if [ ! -f "$NGINX_CONF" ]; then
        cat > "$NGINX_CONF" << 'EOF'
server {
    listen 80;
    server_name localhost;
    
    location / {
        root /usr/share/nginx/html/ruoyi;
        try_files $uri $uri/ /index.html;
        index index.html;
    }
    
    # API反向代理
    location /prod-api/ {
        proxy_pass http://localhost:8080/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # Gzip配置
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";
}
EOF
        print_message "$GREEN" "✅ Nginx配置文件已创建: $NGINX_CONF"
    else
        print_message "$YELLOW" "⚠️  Nginx配置文件已存在，跳过创建"
    fi
}

# 重启Nginx
restart_nginx() {
    print_message "$BLUE" "🔄 重启Nginx..."
    
    # 测试nginx配置
    nginx -t
    
    # 重启nginx
    if systemctl is-active --quiet nginx; then
        systemctl reload nginx
    else
        systemctl restart nginx
    fi
    
    print_message "$GREEN" "✅ Nginx重启完成"
}

# 显示访问信息
show_info() {
    print_message "$GREEN" "\n========================================="
    print_message "$GREEN" "🎉 前端部署完成！"
    print_message "$GREEN" "========================================="
    echo ""
    print_message "$BLUE" "📂 部署目录: $DEPLOY_DIR"
    print_message "$BLUE" "🌐 访问地址: http://localhost"
    print_message "$BLUE" "📝 Nginx配置: $NGINX_CONF_DIR/ruoyi.conf"
    echo ""
    print_message "$YELLOW" "提示："
    print_message "$YELLOW" "  1. 默认管理员账号: admin"
    print_message "$YELLOW" "  2. 默认管理员密码: admin123"
    print_message "$YELLOW" "  3. 确保后端服务已启动在8080端口"
    echo ""
}

# 主函数
main() {
    print_message "$GREEN" "========================================="
    print_message "$GREEN" "    若依前端部署脚本 v1.0"
    print_message "$GREEN" "========================================="
    echo ""
    
    # 执行部署步骤
    check_dependencies
    check_frontend_dir
    
    # 询问是否安装依赖
    read -p "是否需要安装/更新依赖? (y/n, 默认: n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        install_dependencies
    fi
    
    build_frontend
    
    # 询问是否备份
    read -p "是否备份旧版本? (y/n, 默认: y): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Nn]$ ]]; then
        backup_old_version
    fi
    
    deploy_to_nginx
    
    # 询问是否配置nginx
    if [ ! -f "$NGINX_CONF_DIR/ruoyi.conf" ]; then
        read -p "是否创建Nginx配置? (y/n, 默认: y): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Nn]$ ]]; then
            configure_nginx
        fi
    fi
    
    # 询问是否重启nginx
    read -p "是否重启Nginx? (y/n, 默认: y): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Nn]$ ]]; then
        restart_nginx
    fi
    
    show_info
}

# 运行主函数
main "$@"

